#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: zhipeng time: 2018/7/22
from flask import Flask, render_template, url_for, request, redirect, session
import config
from models import User, Conversation, Comment
from exts import db
import __init__
from functools import wraps

app = Flask(__name__)
app.config.from_object(config)
app.config.from_object(__init__)
db.init_app(app)

def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get('user_id'):
            return func(*args, **kwargs)
        else:
            return redirect(url_for('login'))
    return wrapper



@app.route('/')
def index():
    context = {
           'conversations' : Conversation.query.order_by('-create_time').all()
           }
    return render_template('index.html',**context)

@app.route('/detail/<conversation_id>')
def detail(conversation_id):
    conversation_model = Conversation.query.filter(Conversation.id == conversation_id).first()

    
    return render_template('detail.html', conversation = conversation_model)

@app.route('/add_comment', methods = ['POST'])
@login_required
def add_comment():
    content = request.form.get('comment')
    conversation_id = request.form.get('conversation_id')
    
    comment = Comment(content = content)
    user_id = session.get('user_id')
    user = User.query.filter(User.id == user_id).first()
    #通过session的user_id找到写评论的人
    comment.author = user

    conversation = Conversation.query.filter(Conversation.id == conversation_id).first()
    #通过话题的id找到话题
    comment.conversation = conversation
    #让找到的话题成为评论的对象
    db.session.add(comment)
    db.session.commit()
    return redirect(url_for('detail', conversation_id = conversation_id ))
    #重新刷新网页，显示评论
@app.route('/personal_center')
def personal_center():
    return render_template('personal.html')

@app.route('/dou_ni_de')
def dou_ni_de():
    return render_template('dou_ni_de.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        qq_number = request.form.get('qq_number')
        password = request.form.get('password')
        user = User.query.filter(User.qq_number == qq_number, User.password == password).first()
        if user:
            session['user_id'] = user.id
            #如果想在31天内都不需要登录，就要下面这样
            session.permanent = True
            return redirect(url_for('index'))
        else:
            return render_template('alert_html/login.html')
@app.route('/regist', methods=['GET', 'POST'])
def regist():
    if request.method == 'GET':
        return render_template('regist.html')
    else:
        username = request.form.get('username')
        qq_number = request.form.get('qq_number')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        #验证QQ号码是否被注册了
        user = User.query.filter(User.qq_number == qq_number).first()
        if user:
            return render_template('alert_html/regist-repeat.html')
        elif password1 != password2:
            return render_template('alert_html/regist-password.html')
        else:
            user = User(username=username, qq_number=qq_number, password=password2)
            db.session.add(user)
            db.session.commit()
            #注册成功，跳转到登录页面
            return redirect(url_for('login'))

@app.route("/logout")
def logout():
    session.pop('user_id')
    return redirect(url_for('login'))

@app.route("/talk", methods = ['GET', 'POST'])
@login_required
def talk():
    if request.method =='GET':
        return render_template('talk.html')
    else:
        title = request.form.get('title')
        content = request.form.get('content')
        conversation = Conversation(title = title, content = content)
        user_id = session.get('user_id')
        user = User.query.filter(User.id == user_id).first()
        conversation.author = user
        db.session.add(conversation)
        db.session.commit()
        return redirect(url_for('index'))


@app.context_processor
def my_context_processor():
    user_id = session.get("user_id")
    if user_id:
        user = User.query.filter(User.id == user_id).first()
        if user:
            return {'user':user}
    return {}



if __name__ == '__main__':
    app.run(host = '0.0.0.0', port =80)
